<?php
class VisitorInfo_IpLocator
{
    const API_URL = 'https://opendata.baidu.com/api.php?query=%s&co=&resource_id=6006&oe=utf8';
    
    public static function queryLocation($ip)
    {
        if (!filter_var($ip, FILTER_VALIDATE_IP)) {
            return '无效IP';
        }
        
        // 私有IP不查询
        if (self::isPrivateIp($ip)) {
            return '内网IP';
        }
        
        $url = sprintf(self::API_URL, $ip);
        $response = file_get_contents($url);
        $data = json_decode($response, true);
        
        if ($data && $data['status'] == '0' && !empty($data['data'][0]['location'])) {
            return $data['data'][0]['location'];
        }
        
        return '未知';
    }
    
    private static function isPrivateIp($ip)
    {
        return !filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
    }
}



